#! /bin/env python3
# coding: utf-8

import os
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from common.load_cfg import load_cfg


class SendMail:
    def __init__(self, subject, receiver, body=None, attachment_path=None):
        self.subject = subject
        self.receiver = receiver
        self.body = MIMEText(body) if body is not None else body
        self.attachment_path = attachment_path
        self.sender_info = load_cfg('sender_info')
        self.smtp_server = self.sender_info['smtp_server']
        self.sender_user = self.sender_info['sender_user']
        self.sender_pass = self.sender_info['sender_pass']

    def send_mail_info(self):
        self.msg = MIMEMultipart()
        self.msg['Subject'] = self.subject
        self.msg['From'] = self.sender_user
        self.msg['To'] = ','.join(self.receiver) if isinstance(self.receiver, list) else self.receiver
        if self.attachment_path != None:
            attachment = MIMEApplication(open(self.attachment_path, 'rb').read())
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=('utf-8', '', os.path.split(self.attachment_path)[1]))
            self.msg.attach(attachment)
        if self.body != None:
            self.msg.attach(self.body)
        return self.msg

    def login_and_send(self):
        msg = self.send_mail_info()
        smtp = smtplib.SMTP_SSL(self.smtp_server, 465)
        try:
            smtp.login(self.sender_user, self.sender_pass)
            smtp.sendmail(self.sender_user, self.receiver, msg.as_string())
        except Exception as e:
            print(e)


if __name__ == "__main__":
    subject = "test"
    receiver = "yuehua.jiang@jieshun.cn"
    body = 'Hello World!'
    file_path = r"d:\202008.xls"
    a = SendMail(subject, receiver, body)
    a.login_and_send()
